#include "stdafx.h"
#include "Voltage_2700.h"
#include "log.h"

CVoltage2700::CVoltage2700()
{
}

CVoltage2700::~CVoltage2700()
{
}

BOOL CVoltage2700::init(CString address)
{
	log_printf("CVoltage2700::init address=%s \n", (char *)(LPCTSTR)address);
	mDevAddress = address;
	return TRUE;
}

CString CVoltage2700::ReadVoltage(int channel)
{
	//MEAS:VOLT? 10, 0.01, (@101) 
	CString temp;
	temp.Format("(@%d)", channel);
	CString searchCmd="MEAS:VOLT? 20, 0.01, "+temp;

	log_printf("CVoltage2700::ReadVoltage cmd=%s \n", (char *)(LPCTSTR)searchCmd);
	InstrWrite(mDevAddress, searchCmd);

	CString strInstr = "";
	InstrRead(mDevAddress, &strInstr);
	return strInstr;
}

bool CVoltage2700::InstrWrite(CString strAddr, CString strContent) //Write operation 
{
	log_printf("CVoltage2700::InstrWrite address=%s  strContent=%s \n", (char *)(LPCTSTR)strAddr, (char *)(LPCTSTR)strContent);
	ViSession defaultRM,instr; 
	ViStatus status; 
	ViUInt32 retCount; 
	char * SendBuf = NULL;
	char * SendAddr = NULL; 
	bool bWriteOK = false; 
	CString str;
	// Change the address's data style from CString to char*
	SendAddr = strAddr.GetBuffer(strAddr.GetLength()); 
	strcpy(SendAddr,strAddr); 
	strAddr.ReleaseBuffer();

	// Change the command's data style from CString to char*
	SendBuf = strContent.GetBuffer(strContent.GetLength()); 
	strcpy(SendBuf,strContent); 
	strContent.ReleaseBuffer();

	//open a VISA resource 
	status = viOpenDefaultRM(&defaultRM); 
	if (status < VI_SUCCESS) 
	{ 
		AfxMessageBox("No VISA resource was opened!"); 
		return false; 
	} 

	status = viOpen(defaultRM, SendAddr, VI_NULL, VI_NULL, &instr);
	//Write command to the instrument 

	status = viWrite(instr, (unsigned char *)SendBuf, strlen(SendBuf), &retCount); 
	//Close the system 
	status = viClose(instr); 
	status = viClose(defaultRM); 
	return bWriteOK; 
}

bool CVoltage2700::InstrRead(CString strAddr, CString *pstrResult) 
//Read operation 
{
	ViSession defaultRM,instr; 
	ViStatus status; 
	ViUInt32 retCount; 
	char * SendAddr = NULL; 
	unsigned char RecBuf[1024]; 
	bool bReadOK = false; 
	CString str;
	// Change the address's data style from CString to char* 
	SendAddr = strAddr.GetBuffer(strAddr.GetLength()); 
	strcpy(SendAddr,strAddr); 
	strAddr.ReleaseBuffer(); 

	memset(RecBuf,0,1024);
	//Open a VISA resource 
	status = viOpenDefaultRM(&defaultRM); 
	if (status < VI_SUCCESS) 
	{ 
		// Error Initializing VISA...exiting

		AfxMessageBox("No VISA resource was opened!"); 
		return false; 
	}
	//Open the instrument 
	status = viOpen(defaultRM, SendAddr, VI_NULL, VI_NULL, &instr);
	//Read from the instrument 
	status = viRead(instr, RecBuf, 1024, &retCount);
	//close the system 
	status = viClose(instr); 
	status = viClose(defaultRM); 
	(*pstrResult).Format("%s",RecBuf); 
	return bReadOK; 
}